﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace TreeBuilder
{
    class PasteAction : TreeOperationAction
    {
        private readonly CopyObjectDTO _copy;

        public PasteAction(DottedCanvas canvas, CopyObjectDTO copy)
            :base(canvas)
        {
            _copy = copy;
        }

        public override void Execute()
        {
            var data = _copy;
            var list = data.Nodes.Cast<object>().Union(data.Frames).Union(data.Lines).Union(data.Arrows).Union(data.Triangles);

            foreach (var o in list)
            {
                AddToTree((UIElement) o);
            }

            var nodes = data.Nodes.Cast<INode>().Union(data.Frames).ToList();
            foreach (var node in nodes)
            {
                node.Guid = Guid.NewGuid();
                node.TopCenter = node.TopCenter;
                node.IsSelected = true;
            }
            nodes.OrderBy(x => x.TopCenter.Y).ThenBy(x => x.LeftCenter.X).Cast<UIElement>().First().Focus();


            var binders = data.Lines.Cast<IBinder>().Union(data.Arrows).Union(data.Triangles);
            foreach (var binder in binders)
            {
                binder.RefreshPoints();
            }
        }

        public override void Undo()
        {
            var data = _copy;

            foreach (var node in data.Nodes.Cast<INode>().Union(data.Frames))
            {
                node.IsSelected = false;
            }
            
            var list = data.Nodes.Cast<object>().Union(data.Frames).Union(data.Lines).Union(data.Arrows).Union(data.Triangles);
            foreach (var o in list)
            {
                RemoveFromTree((UIElement)o);
            }

            Canvas.Focus();
        }
    }
}
